<script setup>

import {computed, reactive, ref, watch, provide, toRaw, getCurrentInstance, onMounted, nextTick, watchEffect} from 'vue'
import cheerio from "cheerio";
import $ from "jquery"
import HilightedSentence from "@/components/HilightedSentence.vue";
import MarkLijuSingleEntry from "@/components/MarkLijuSingleEntry.vue";
import ButtonsTest from "@/ButtonsTest.vue";
// import * as $http from "cheerio/lib/api/traversing";
// import YoudaoLijuPatternMarkingTemp from "@/dtos/YoudaoLijuPatternMarkingTemp"
import {YoudaoLijuPatternMarkingTemp} from "@/dtos/YoudaoLijuPatternMarkingTemp";
import {
  Delete,
  ArrowUp,
  Plus,
  Close
} from '@element-plus/icons-vue'

import {clearAndPushAll} from "@/utils/ArrayUtil";
import FormCheckGroups from "@/components/FormCheckGroups.vue";
import TagsTest from "@/TagsTest.vue";
import Test1Comp from "@/testCompGroupA/Test1Comp.vue";
import Test2Comp from "@/testCompGroupB/Test2Comp.vue";
import Test3Comp from "@/testCompGroupC/Test3Comp.vue";
import Test4Comp from "@/testCompGroupC/Test4Comp.vue";
import Test5Comp from "@/testCompGroupC/Test5Comp.vue";
import Test6Comp from "@/testCompGroupC/Test6Comp.vue";
import Test7Comp from "@/testCompGroupC/Test7Comp.vue";
import Test8Comp from "@/testCompGroupC/Test8Comp.vue";
import TagBaseWord from "@/components/PhraseItComp/TagBaseWord.vue";
import PickedDoneFormCountLijusShowingButton from "@/components/PickedDoneFormCountLijusShowingButton.vue";
import PhraseOWordSettledSingleEntryView from "@/components/PhraseItComp/PhraseOWordSettledSingleEntryView.vue";
import TinyMCETest1 from "@/testCompGroupC/TinyMCETest1.vue";

import {isStringNotBlank, isStringBlank, contains} from "@/utils/StringUtil";

import {
  BatchOperType,
  globalContextDataKey1,
  globalContextKey1,
  globalContextKey2,
  globalContextSw, globalShortCutKeysEventCenter
} from "@/constants/gConstants";

import {
  difference,
  orderBy,
  intersection,
  assignIn,
  pick,
  assignInWith,
  groupBy,
  max,
  toPairs,
  sortedIndexBy, remove
} from "lodash-unified";
import FormsCountBtn from "@/components/FormsCountBtn.vue";
import BatchOverWritingTags from "@/components/WordFormedTag/BatchOverWritingTags.vue";
import BatchOverWritingTag from "@/components/WordFormedTag/BatchOverWritingTag.vue";
import WordFormedCheckTag from "@/components/WordFormedTag/WordFormedCheckTag.vue";
import WordFormedTagGroup from "@/components/WordFormedTag/WordFormedTagGroup.vue";

import axios from "axios";
import {plainToInstance, instanceToPlain} from 'class-transformer';
import 'reflect-metadata'
import {isEmptyObj} from "@/utils/ObjectUtils";

const {Bus} = getCurrentInstance().appContext.config.globalProperties;

const currDomainPort = 'http://localhost:5173/';

const routes = {
  '/buttons': ButtonsTest
}
const currentPath = ref(window.location.hash)
window.addEventListener('hashchange', () => {
  currentPath.value = window.location.hash
})
const currentView = computed(() => {
  return routes[currentPath.value.slice(1) || '/']
})

let verbFormMapping = reactive(new Map());

const count = ref('111');
let inputMatchPatternRef = ref();
let inputMatchPatternV = ref('');

let fetchYoudaoLijus = ref();
let fetchYoudaoLijusV = ref('');
let fetchLijuButton = ref();

let formsInputV = ref('');

let rawVerbsInFetchYoudaoLijus;
let rawVerbsInInputMatchPattern;

let engPartRegex = /\/\/eng\/(.*)\/(?=\/chi)|\/\/eng\/(.*)\//;
// let engPartRegex = /\/\/eng\/(.*)\//;
let chiPartRegex = /\/\/chi\/(.*)\//;
let mulformTagPatternOfFetch = '//v.';
let mulformTagPatternOfInputMatch = mulformTagPatternOfFetch + " ";
let maskNotMatched = ref(false);
let invertInputPatternMatchRule = ref(false);
let batchIndividual = ref(false);
let formNoSelectDeleteMode = ref(false);
let thisPageFilterShowing = ref(false);
let invertFilterTheFormCountsRule = ref(false);
let filterAllAndMode = ref(false); //否则为或
let exactOrInclude = ref(false); //且的情况下是精确还是包含，false是包含-->子集

let anyIndividualIsEditing = ref(0);
let readingModeSw = ref(false);
let allDetailing = ref(false);

let legalInputMatchPattern = ref(false);

const batchDeletingTheForm = ref('');

provide(globalContextSw, {
  batchIndividual,
  formNoSelectDeleteMode,
  batchDeletingTheForm,
  anyIndividualIsEditing,
  readingModeSw
})

function maskNotMatchedChanged() {
  if (!maskNotMatched.value) {
    invertInputPatternMatchRule.value = false;
  }
}

let replacedAllFormedFetchKeywordsArr = reactive([]);

function fetchYoudaoLijusUpped() {
  let fetchPattern = fetchYoudaoLijusV.value.trim();
  if (fetchPattern.match(mulformTagPatternOfFetch)) {
    rawVerbsInFetchYoudaoLijus = fillVerbFormsMapping(fetchPattern, new RegExp(mulformTagPatternOfFetch, "g")).extractedRawVerbs;
  }
}

let fetchedYoudaoLijuResultMap = reactive(new Map());


let flatedYoudaoLijuPatternMarkingTempArr = reactive([]);

let clearShowingSwitch = ref(false);


let showingFetchedYoudaoLijuResultList = reactive([]);
let fetchedYoudaoLijuEntryIdMap = reactive(new Map());

watchEffect(()=>{
    // console.log("watchedEffect P01");
    let orderedFetchedYoudaoLijuResult = orderBy([...fetchedYoudaoLijuResultMap.entries()],
        formedFetchKeyToLijuArrEntry => replacedAllFormedFetchKeywordsArr.findIndex(
            formedFetchKey => formedFetchKey === formedFetchKeyToLijuArrEntry[0]
        ),
        ["asc"]
    );

    clearAndPushAll(showingFetchedYoudaoLijuResultList,[...orderedFetchedYoudaoLijuResult]);
    fetchedYoudaoLijuEntryIdMap.clear();
    let theFlatedArr = [...orderedFetchedYoudaoLijuResult.flatMap(entry => entry[1])];

    clearAndPushAll(flatedYoudaoLijuPatternMarkingTempArr,theFlatedArr);

    theFlatedArr.forEach(theEntry=>{
        theEntry.toShow = false;
        fetchedYoudaoLijuEntryIdMap.set(theEntry.uniqueId,theEntry);
    })
})

watchEffect(()=>{
    // console.log("change showing effect watched");
    filterShowingLijuArr(flatedYoudaoLijuPatternMarkingTempArr);
})

function testSome1(){
    // console.log("showingFetchedYoudaoLijuResultList",showingFetchedYoudaoLijuResultList);
    // console.log("fetchedYoudaoLijuEntryIdMap",fetchedYoudaoLijuEntryIdMap);
}

function filterShowingLijuArr(toFilterYoudaoLijuEntryArr) {
    return toFilterYoudaoLijuEntryArr.filter(youdaoLijuPatternMarkingTempEntry => {

        let pickDoneFormsCountsArrOf = [...youdaoLijuPatternMarkingTempEntry.pickDoneFormsCountCheckedListMap.values()].flatMap(ele => ele);
        let theIntersectedLength = intersection(pickDoneFormsCountsArrOf, filterTheResultFormsCountsCheckedList.value).length;

        let exactAnd = pickDoneFormsCountsArrOf.length !== 0
            && pickDoneFormsCountsArrOf.length === filterTheResultFormsCountsCheckedList.value.length
            && pickDoneFormsCountsArrOf.length === theIntersectedLength;//且对应完全一样？所选formcounts和当前例句的pickdoenformcounts 且得完全一样？


        let includingAllAnd = pickDoneFormsCountsArrOf.length !== 0
            && theIntersectedLength === filterTheResultFormsCountsCheckedList.value.length;
        //todo 上面&&pickDoneFormsCountsArrOf.length===filterTheResultFormsCountsCheckedList.value.length去掉即可?

        let theAndRuleResult = exactOrInclude.value ? exactAnd : includingAllAnd;

        let hasTheFilteringResultFormsCountsCheckedList =
            filterTheResultFormsCountsCheckedList.value.length === 0
            || (filterTheResultFormsCountsCheckedList.value.length > 0 && filterAllAndMode.value ? theAndRuleResult : theIntersectedLength > 0);
        // && filterAllAndMode.value?exactAnd:theIntersectedLength>0);
        //=== 和filterTheResultFormsCountsCheckedList.value.length相等代表交集等于filterTheResultFormsCountsCheckedList.value.length本身？ 真子集？
        //todo 找到真子集更靠谱的方法。 //lodash?

        // invertFilterTheFormCountsRule.value hasTheFilteringResultFormsCountsCheckedList
        // true true ===>false
        // true false ===>true
        // false true ===>true
        // false false ===>false

        let filterRuleResult = invertFilterTheFormCountsRule.value ^ hasTheFilteringResultFormsCountsCheckedList;


        let ifInputMatchShow = true;
        if (maskNotMatched.value && legalInputMatchPattern.value) {
            ifInputMatchShow = youdaoLijuPatternMarkingTempEntry.inputPatternMatched;
            // if (!invertInputPatternMatchRule.value) {
            //     return youdaoLijuPatternMarkingTempEntry.inputPatternMatched;
            // } else {
            //     return !youdaoLijuPatternMarkingTempEntry.inputPatternMatched;
            // }
        }

        let ifInputMatchRuleResult = invertInputPatternMatchRule.value ^ ifInputMatchShow;
        // true true ===>false
        // true false ===>true
        // false true ===>true
        // false false ===>false

        let result = filterRuleResult && ifInputMatchRuleResult;
        youdaoLijuPatternMarkingTempEntry.toShow=Boolean(result);
        return result
    });
}

let cptShowingFetchedYoudaoLijuResultList = computed(() => {
  clearAndPushAll(markLijuSingleEntrys, []);
  // console.log("cleared the markLijuSingleEntrys");
  currEntryFocusingIdxRef.value = -1;
  let resultArr = [];
  // console.log("computing");
  if (!clearShowingSwitch.value && replacedAllFormedFetchKeywordsArr) {
    let mappedArr = replacedAllFormedFetchKeywordsArr.map(replacedKeyword => {
      let filteredArr;
      if (fetchedYoudaoLijuResultMap.get(replacedKeyword)) {
        filteredArr = filterShowingLijuArr(fetchedYoudaoLijuResultMap.get(replacedKeyword));
      }
      // filteredArr.forEach((ele,idx)=>{ele.aIdx = idx});
      // filteredArr = filteredArr.slice(0,filteredArr.length-2);
      return {replacedKeyword: replacedKeyword, resultShowingList: filteredArr};
    })

    resultArr = [...mappedArr];
  }
  // else {
  //     return [];
  // }
  return resultArr;
});

// let reactiveCptShowingFetchedYoudaoLijuResultList = reactive(cptShowingFetchedYoudaoLijuResultList);

let flatedCptShowingFetchedYoudaoLijuResultList = computed(() => {
  let resultArr = cptShowingFetchedYoudaoLijuResultList.value.flatMap(ele => {
    return ele.resultShowingList ? ele.resultShowingList : [];
  });

  resultArr.forEach((ele, idx) => {
    ele.aIdx = idx
    // if(idx!==resultArr.length-1){
    //     ele.nextEntryRef = resultArr[idx+1];
    // }else{
    //     ele.nextEntryRef = resultArr[0];
    // }
  });
  return resultArr;
})

// watchEffect(()=>{
//     flatedCptShowingFetchedYoudaoLijuResultList.forEach(theLijuEntry=>{
//         fetchedYoudaoLijuEntryIdMap.get(theLijuEntry.uniqueId).toShow = true;
//     })
// })

// watchEffect(() => {
//   let aaa = flatedCptShowingFetchedYoudaoLijuResultList;
//   // console.log("the showing changed",aaa);
// })


function reInitAllCommonSwitch() {
  readingModeSw.value = false;
  // batchFormsCntPickSw.value = false;
  anyIndividualIsEditing.value = 0;
  batchIndividual.value = false;
}

function fetchYoudaoLijusFunc(e) {

  reInitAllCommonSwitch();

  // fetchedYoudaoLijuResultMap = new Map();
  fetchedYoudaoLijuResultMap.clear();
  // let theSentence = 'aaa bb ccc merge with into merge//v. and dkdkdk fly//v. sss to ddd merge//v. of nnnns'

  let fetchYoudaoLijusValue = fetchYoudaoLijusV.value;
  //保持replacedAllFormedFetchKeywordsArr的reactive性，才能在computed依赖它时保持重新计算。//且要保持在第一次computed的对象相同


  clearAndPushAll(replacedAllFormedFetchKeywordsArr, [fetchYoudaoLijusValue]);

  if (fetchYoudaoLijusValue.trim().match(mulformTagPatternOfFetch)) {
    if (rawVerbsInFetchYoudaoLijus) {
      for (const rawVerb of rawVerbsInFetchYoudaoLijus) {
        let verbFormsSet = verbFormMapping.get(rawVerb);

        let replacedArr = replacedAllFormedFetchKeywordsArr.flatMap(aSentence => {
          return recursiveReplace(aSentence, rawVerb, verbFormsSet)
        });

        clearAndPushAll(replacedAllFormedFetchKeywordsArr, replacedArr);
      }
    }
  }


  function recursiveReplace(theSentence, rawVerb, toFormedVerbSets) {
    let matchAndRepplaceParttern = rawVerb + mulformTagPatternOfFetch;
    let theMatched = theSentence.match(matchAndRepplaceParttern);
    let preSentence = theSentence.substring(0, theMatched.index + matchAndRepplaceParttern.length);//match到前的部分
    let restSentence = theSentence.substring(theMatched.index + matchAndRepplaceParttern.length);//剩余部分

    let restMatched = restSentence.match(matchAndRepplaceParttern);
    let preRawSentence = preSentence.substring(0, preSentence.length - mulformTagPatternOfFetch.length);
    let preReplacedArr = [preRawSentence, ...[...toFormedVerbSets].map((toFormedVerb) => preSentence.replace(new RegExp(matchAndRepplaceParttern), toFormedVerb))];

    let restReplaceArr;
    if (restMatched) {
      restReplaceArr = recursiveReplace(restSentence, rawVerb, toFormedVerbSets);
      return preReplacedArr.flatMap(prePart => {
        return restReplaceArr.flatMap(restPart => {
          return prePart + restPart
        })
      });
    } else {
      return preReplacedArr.map(preReplacedPart => preReplacedPart + restSentence);
    }
  }

  // let encodedResultArr = resultArr.map(ele => encodeURIComponent(ele));
  for (const fetchKeyWord of replacedAllFormedFetchKeywordsArr) {
    getOutSourceYoudao('/result?word=lj%3A' + encodeURIComponent(fetchKeyWord) + '&lang=en', extractYoudaoLijuFuncCurryFetchKeyword(fetchKeyWord));
  }

  // console.log();
}


let buttonDisabled = ref(false);

function disableFetchYoudaoLijus(e) {
  fetchYoudaoLijus.value.disabled = "disabled";
  // fetchLijuButton.value.disabled = "disabled";
  buttonDisabled.value = true;
}

function enableFetchYoudaoLijus(e) {
  fetchYoudaoLijus.value.disabled = null;
  buttonDisabled.value = false;
}

const getCssVarName = (type) => {
  return `--el-box-shadow${type ? '-' : ''}${type}`
}

let theWord = 'fly';


watch(verbFormMapping, (oldVal, newVal) => {
  function allFetchedMulFormsFor(rawVerbsSet) {
    let allFetched = true;
    if (rawVerbsSet) {
      // rawVerbsInFetchYoudaoLijus = new Set();
      for (const theRawVerb of rawVerbsSet) {
        // newVal = new Map();
        let verFormsSet = newVal.get(theRawVerb);
        if (!verFormsSet || !verFormsSet.size || (verFormsSet.size && verFormsSet.size === 0)) {
          allFetched = false;
          break;
        }
      }
    }

    return allFetched;
  }

  if (rawVerbsInFetchYoudaoLijus && rawVerbsInFetchYoudaoLijus.size > 0 && allFetchedMulFormsFor(rawVerbsInFetchYoudaoLijus)) {
    buttonDisabled.value = false;
  } else {
    buttonDisabled.value = true;
  }

  if (rawVerbsInInputMatchPattern && rawVerbsInInputMatchPattern.size > 0 && allFetchedMulFormsFor(rawVerbsInInputMatchPattern)) {
    hilightPatternMatched();
  }
});

function clearAllHilis() {
  flatedYoudaoLijuPatternMarkingTempArr.forEach((ele) => {
    ele.clearAllParts();
  });
}

function buildHiliParts(theParts, chiPartMatched) {
  if (!theParts instanceof YoudaoLijuPatternMarkingTemp.HilightParts) {
    throw new Error("theParts should be of YoudaoLijuPatternMarkingTemp.HilightParts");
  }

  let chiPrePartText = theParts.originText.substring(0, chiPartMatched.index);
  let chiRailPartText = theParts.originText.substring(chiPartMatched.index + chiPartMatched[0].length);
  theParts.prePartsArr.push({text: chiPrePartText, isBold: false});
  theParts.hilightPartsArr.push({text: chiPartMatched[0], isBold: false});
  theParts.railPartsArr.push({text: chiRailPartText, isBold: false});
  theParts.toHili = true;
}

function hilightPatternMatched() {

  let inputMatchPatternValue = inputMatchPatternV.value;
  let legalPatternMatched = inputMatchPatternValue.trim().match(engPartRegex) || inputMatchPatternValue.trim().match(chiPartRegex);

  if (legalPatternMatched) {
    let theEngPart;
    let theChiPart;

    let theEngMatched = inputMatchPatternValue.trim().match(engPartRegex);

    for (let i = 1; i < theEngMatched?.length; i++) {
      if (theEngMatched[i]) {
        theEngPart = theEngMatched[i];
        break;
      }
    }

    let theChiMatched = inputMatchPatternValue.trim().match(chiPartRegex);
    if (theChiMatched && theChiMatched[1]) {
      theChiPart = theChiMatched[1];
    }

    if (theEngPart && theEngPart.match(new RegExp(mulformTagPatternOfInputMatch))) {
      let theRawVerbsOfInputMatch = parseTaggedRawVerbs(inputMatchPatternValue, new RegExp(mulformTagPatternOfInputMatch, 'g'));

      [...theRawVerbsOfInputMatch].forEach(rawVerb => {
        let joinnedFormVerbsPattern = '(' + rawVerb + '|' + [...verbFormMapping.get(rawVerb)].join('|') + ')';
        theEngPart = theEngPart.replaceAll(new RegExp(rawVerb + mulformTagPatternOfInputMatch, "g"), joinnedFormVerbsPattern);
      })
    }

    // fetchedYoudaoLijuResultMap = new Map();
    // let allEntries = fetchedYoudaoLijuResultMap.entries();

    clearAllHilis();

    // notShowAny();
    // let engPatternFiltered = flatedYoudaoLijuPatternMarkingTempArr.value.filter(toHilightEntry => {
    flatedYoudaoLijuPatternMarkingTempArr.forEach(toHilightEntry => {
      let theEngParts = toHilightEntry.engHiliParts;
      let theChiParts = toHilightEntry.chiHiliParts;

      let engPartMatched;
      let chiPartMatched;
      if (isStringNotBlank(theEngPart)) {
        engPartMatched = theEngParts.originText.match(new RegExp(theEngPart, "i"));
      }

      if (isStringNotBlank(theChiPart)) {
        chiPartMatched = theChiParts.originText.match(new RegExp(theChiPart));
      }

      if (isStringNotBlank(theEngPart) && engPartMatched && isStringBlank(theChiPart)) {
        theEngParts.inputPatternMatched = true;
        buildHiliParts(theEngParts, engPartMatched);
      } else if (isStringNotBlank(theChiPart) && chiPartMatched && chiPartMatched[0] !== chiPartMatched.input && isStringBlank(theEngPart)) {
        theChiParts.inputPatternMatched = true;
        buildHiliParts(theChiParts, chiPartMatched);
      } else if (isStringNotBlank(theEngPart) && engPartMatched && isStringNotBlank(theChiPart) && chiPartMatched && chiPartMatched[0] !== chiPartMatched.input) {
        theEngParts.inputPatternMatched = true;
        buildHiliParts(theEngParts, engPartMatched);
        theChiParts.inputPatternMatched = true;
        buildHiliParts(theChiParts, chiPartMatched);
      }
    });
  } else {
    clearAllHilis();
  }
}

// getOutSourceYoudao('/result?word=' + theWord + '&lang=en', parseYoudaoWordWfs);

function youdaoWordWfsParseFuncCurryWithWord(word) {
  function parseYoudaoWordWfs(wordMainInfo) {
    let $cheerioed = cheerio.load(wordMainInfo, {xmlMode: false});
    let wordWfsLess = $cheerioed('.word-wfs-less');

    function extractWfses(wfs) {
      return wordWfsLess.find('.wfs-name:contains("' + wfs + '")')
          .parents('li.word-wfs-cell-less')
          .find('.transformation')
          .text();
    }

    let thePlural = extractWfses('复数');
    let theThirdPersonSingular = extractWfses('第三人称单数');
    let thePresentParticiple = extractWfses('现在分词');
    let thePastSimples = extractWfses('过去式').split('或');
    let thePastParticiples = extractWfses('过去分词').split('或');
    let theComparative = extractWfses('比较级');
    let theSuperlative = extractWfses('最高级');

    let verbForms = [];
    verbForms.push(theThirdPersonSingular);
    verbForms.push(...thePastSimples);
    verbForms.push(...thePastParticiples);
    verbForms.push(thePresentParticiple);

    let verbFormSets = new Set();

    verbFormSets.add(theThirdPersonSingular);

    for (const thePastSimple of [...thePastSimples]) {
      verbFormSets.add(thePastSimple);
    }

    for (const thePastParticiple of [...thePastParticiples]) {
      verbFormSets.add(thePastParticiple);
    }
    verbFormSets.add(thePresentParticiple);


    let verbFormObject = {};
    verbFormObject[word] = verbFormSets;
    // verbFormMapping = new Map();
    verbFormMapping.set(word, verbFormSets);
    // for (const verbForm of verbFormSets) {
    //   getOutSourceYoudao('/result?word=lj%3A' + encodeURIComponent(verbForm) + '&lang=en', extractYoudaoLiju);
    // }


    // console.log('');
  }

  return parseYoudaoWordWfs;
}

// cheerioIt()

function getOutSourceYoudao(uri, callback) {
  getOutSource('youdao', uri, callback);
}

function getOutSource(src, uri, callback) {

  // let respContent = '';
  let targetUrl = currDomainPort + src + uri;
  $.get(
      {
        // url: "youdao/result?word=lj%3Amerges%20in%20to&lang=en"
        url: targetUrl
      }, function (data, status) {
        callback(data);
      });

  // return respContent;
}

function extractYoudaoLijuFuncCurryFetchKeyword(fetchKeyWord) {
  function extractYoudaoLiju(html) {
    // cheerio.load(html,{xmlMode: true, decodeEntities: false});
    let $cheerioed = cheerio.load(html, {xmlMode: false});
    let sentences = $cheerioed('#catalogue_sentence');

    let lis = sentences.find(".dict-book .trans-container>ul>li");
    let resultArr = [];

    fetchedYoudaoLijuResultMap.set(fetchKeyWord, resultArr);
    lis.each(function (idx, theLi) {
      let theEng = $cheerioed(theLi).find('.sen-eng').text();
      let theChi = $cheerioed(theLi).find('.sen-ch').text();
      let theSecondary = $cheerioed(theLi).find('.secondary').text();
      //
      // count.value += $cheerioed(theLi).find('.sen-eng').text();

      resultArr.push(new YoudaoLijuPatternMarkingTemp(theEng, theChi, theSecondary));
    })
  }

  return extractYoudaoLiju;
}


function parseTaggedRawVerbs(inputPatternValue, mulformPattern) {
  let extractedRawVerbs = new Set();

  let matchVerbTagIter = inputPatternValue.trim().matchAll(mulformPattern);

  [...matchVerbTagIter].forEach((matchVerbTag) => {
    let splits = inputPatternValue.substring(0, matchVerbTag.index).split(/\b/);
    let theMatchedVerbRawWord = splits[splits.length - 1];
    extractedRawVerbs.add(theMatchedVerbRawWord);
  });
  return extractedRawVerbs;
}

function fillVerbFormsMapping(inputPatternValue, mulformPattern) {

  let extractedRawVerbs = parseTaggedRawVerbs(inputPatternValue, mulformPattern);

  let fillingResult =
      {
        extractedRawVerbs: extractedRawVerbs,
        newVerbFound: false
      };

  [...extractedRawVerbs].forEach((theMatchedVerbRawWord) => {
    if (!verbFormMapping.has(theMatchedVerbRawWord)) {
      fillingResult.newVerbFound = true;
      // verbFormMapping = new Map();
      verbFormMapping.set(theMatchedVerbRawWord, new Set());
      getOutSourceYoudao('/result?word=' + theMatchedVerbRawWord + '&lang=en', youdaoWordWfsParseFuncCurryWithWord(theMatchedVerbRawWord));
    }
  });
  return fillingResult;
}

function inputMatchKeyUpped(e) {

  let inputMatchPatternValue = inputMatchPatternV.value;
  legalInputMatchPattern.value = inputMatchPatternValue.trim().match(engPartRegex) || inputMatchPatternValue.trim().match(chiPartRegex);
  if (legalInputMatchPattern.value) {
    let fillingResult = fillVerbFormsMapping(inputMatchPatternValue, new RegExp(mulformTagPatternOfInputMatch, 'g'));
    rawVerbsInInputMatchPattern = fillingResult.extractedRawVerbs;
    if (!fillingResult.newVerbFound) {
      hilightPatternMatched();
    }
  } else {
    clearAllHilis();
  }
}

function clearInputMatchPattern(e) {
  inputMatchPatternV.value = '//eng/';
  legalInputMatchPattern.value = false;
  inputMatchPatternRef.value.focus();
  hilightPatternMatched();
}

const nounsCheckList = ref(['n.3', 'n.5', 'n.6']);
const verbsCheckList = ref(['v.1', 'v.5']);

const buttonsTestVisible = ref(false);
const tagsTestVisible = ref(false);
const testCompVisible = ref(false);
const testModelDefineVisible = ref(false);
const testComp3Visible = ref(false);
const testComp4Visible = ref(false);
const testComp5Visible = ref(false);
const testComp6Visible = ref(false);
const testComp7Visible = ref(false);


const chooseThisTagAllLijusVisible = ref(false);
const batchFormsCntPickSw = ref(false);

const batchOperType = ref(BatchOperType.None);

let formsCountMap = reactive(new Map());

//formsCountMap有变化时根据formsCountMap初始化formsCountCheckedListMap
watch(formsCountMap, (newFormsCountMap) => {
  flatedYoudaoLijuPatternMarkingTempArr.forEach(youdaoLijuPatternMarkingTemp => {
    [...newFormsCountMap.keys()].forEach(form => {
      if (!youdaoLijuPatternMarkingTemp.formsCountCheckedListMap.has(form)) {
        youdaoLijuPatternMarkingTemp.formsCountCheckedListMap.set(form, []);
      }
    })
  })
})

function batchDeleteAllPickedDoneOfForm(form) {
  batchDeletingTheForm.value = form;
  batchOperType.value = BatchOperType.Deleting;
}

/**
 * 批量修改操作部分 start
 */
function batchMatchOverWriteAllTempPick() {
  batchOperType.value = BatchOperType.OverWriting;
  clearAllLijuEntryBatchModifyPendingConfirm();

  /**
   * new start
   */

  let emptyFormsCountMap = formsCountMap.size === 0 || [...formsCountMap.values()].every(ele => ele?.checkedList?.length === 0);
  if (emptyFormsCountMap) {
    return;
  }

  flatedCptShowingFetchedYoudaoLijuResultList.value.forEach(showingLijuEntry => {

    [...formsCountMap.keys()].forEach(form => {
      let theFormBatchCheckedList = [...toRaw(formsCountMap.get(form).checkedList)];
      let theFormBatchCheckedListEmpty = !theFormBatchCheckedList || theFormBatchCheckedList?.length === 0;

      if (!theFormBatchCheckedListEmpty) {
        showingLijuEntry.batchModifyPendingConfirm.toOverWriteFormsCountsListMap.set(form, orderBy(theFormBatchCheckedList));
      } else if (formNoSelectDeleteMode.value) {
        showingLijuEntry.batchModifyPendingConfirm.toOverWriteFormsCountsListMap.set(form, []);
      }
    })

  });

  /**
   * new end
   */


  /**
   * to delete start
   */
  // let emptyFormsCountMap = formsCountMap.size === 0 || [...formsCountMap.values()].every(ele => ele?.checkedList?.length === 0);
  // if (emptyFormsCountMap) {
  //     return;
  // }
  // flatedCptShowingFetchedYoudaoLijuResultList.value.forEach(showingLijuEntry => {
  //     [...formsCountMap.keys()].forEach(form => {
  //         let overWriteBatchMatchedArr = [...toRaw(formsCountMap.get(form).checkedList)];
  //         showingLijuEntry.formsCountTempPickListMap.set(form, orderBy(overWriteBatchMatchedArr));
  //     })
  // });

  /**
   * to delete end
   */
}

// function inputHasTheForm(theForm){
//     return formsInputV.value.split(' ').findIndex(form=>theForm===form.substring(0,form.lastIndexOf('.')).trim())>=0;
// }

function clearAllLijuEntryBatchModifyPendingConfirm() {
  flatedYoudaoLijuPatternMarkingTempArr.forEach(lijuEntry => {
    lijuEntry.clearBatchModifyPendingConfirmAll();
    // clearAndPushAll(,[]);
  });
}

function batchMatchAddAllTempPick() {
  batchOperType.value = BatchOperType.Adding;
  clearAllLijuEntryBatchModifyPendingConfirm();
  /**
   * new start
   */
  flatedCptShowingFetchedYoudaoLijuResultList.value.forEach(showingLijuEntry => {
    [...formsCountMap.keys()].forEach(form => {
      let differencedBatchMatchedArr = difference([...toRaw(formsCountMap.get(form).checkedList)],
          showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form) ? [...toRaw(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form))] : []);
      showingLijuEntry.batchModifyPendingConfirm.toAddFormsCountsListMap.set(form, orderBy(differencedBatchMatchedArr));
    })
    // clearAndPushAll(showingLijuEntry.formsCountTempPickListMap,[]);

  });
  /**
   * new end
   */

  /**
   * to delete start
   */
  // flatedCptShowingFetchedYoudaoLijuResultList.value.forEach(showingLijuEntry => {
  //     [...formsCountMap.keys()].forEach(form => {
  //         let differencedBatchMatchedArr = difference([...toRaw(formsCountMap.get(form).checkedList)], showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form) === undefined ? [] : [...toRaw(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form))]);
  //         showingLijuEntry.formsCountTempPickListMap.set(form, orderBy(differencedBatchMatchedArr));
  //     })
  //     // clearAndPushAll(showingLijuEntry.formsCountTempPickListMap,[]);
  //
  // });

  /**
   * to delete end
   */
  // console.log("3:", formsCountMap);
  // console.log("4:", flatedCptShowingFetchedYoudaoLijuResultList);
}

function confirmAllBatchTempPickIntoPickDone() {
  flatedCptShowingFetchedYoudaoLijuResultList.value.forEach(showingLijuEntry => {
    /**
     * new start
     */

    // switch (batchOperType.value) {
    //     case BatchOperType.OverWriting:
    //         console.log("batch overwriting");
    //         break;
    //     case BatchOperType.Adding:
    //         console.log("batch Adding");
    //         break;
    //     case BatchOperType.Deleting:
    //         console.log("batch Deleting");
    //         break;
    // }
    if (batchOperType.value === BatchOperType.OverWriting) {
      [...showingLijuEntry.batchModifyPendingConfirm.toOverWriteFormsCountsListMap.keys()].forEach(form => {
        let resultArr = [];
        let existedPickDoneArr = toRaw(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form));
        let toOverWriteFormsCountsArr = showingLijuEntry.batchModifyPendingConfirm.toOverWriteFormsCountsListMap.get(form);
        let noMoreOverWriteMode = toOverWriteFormsCountsArr?.noMoreOverWriteMode;
        toOverWriteFormsCountsArr = toRaw(toOverWriteFormsCountsArr);
        resultArr.push(...(toOverWriteFormsCountsArr ? toOverWriteFormsCountsArr : []));
        if (toOverWriteFormsCountsArr) {
          if (existedPickDoneArr) {
            if (noMoreOverWriteMode) {
              resultArr.push(...existedPickDoneArr);
              resultArr = [...new Set(resultArr)];
            }
            clearAndPushAll(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form), resultArr);
          } else if (toOverWriteFormsCountsArr.length > 0) {
            showingLijuEntry.pickDoneFormsCountCheckedListMap.set(form, orderBy(resultArr, [], ['asc']));
          }
          //如果 toOverWriteFormsCountsArr为空，代表没有对应key的设置。且existedPickDoneArr没有已存在的pickedDone，就什么也不用做
        }
      });
    } else if (batchOperType.value === BatchOperType.Adding) {
      [...showingLijuEntry.batchModifyPendingConfirm.toAddFormsCountsListMap.keys()].forEach(form => {
        let resultArr = [];
        let existedPickDoneArr = toRaw(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form));
        let toAddFormsCountsArr = toRaw(showingLijuEntry.batchModifyPendingConfirm.toAddFormsCountsListMap.get(form));

        resultArr.push(...(existedPickDoneArr ? existedPickDoneArr : []))
        resultArr.push(...(toAddFormsCountsArr ? toAddFormsCountsArr : []))
        if (resultArr.length > 0) {
          resultArr = orderBy(resultArr, [], ['asc']);
          if (existedPickDoneArr) {
            clearAndPushAll(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form), resultArr);
          } else {
            showingLijuEntry.pickDoneFormsCountCheckedListMap.set(form, resultArr);
          }
        }
      });
    } else if (batchOperType.value === BatchOperType.Deleting) {
      if (batchDeletingTheForm.value.length > 0) {
        let resultArr = [];
        let existedPickDoneArr = toRaw(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(batchDeletingTheForm.value.trim()));
        let theFormsCountMapCheckedListOfForm = formsCountMap.get(batchDeletingTheForm.value.trim())?.checkedList;
        resultArr = difference([...(existedPickDoneArr ? existedPickDoneArr : [])], [...toRaw(theFormsCountMapCheckedListOfForm ? theFormsCountMapCheckedListOfForm : [])]);
        if (existedPickDoneArr) {
          clearAndPushAll(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(batchDeletingTheForm.value.trim()), resultArr);
        }
      }
    }

    /**
     * new end
     */

    /**
     * to delete start.
     */

    // [...showingLijuEntry.formsCountTempPickListMap.keys()].forEach(form => {
    //     let resultArr = [];
    //     let existedPickDoneArr = toRaw(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form));
    //
    //     if (!batchOverWriting.value) {
    //         //添加模式不管是否为(未选删除)，都要把已有的pickeDone的加进去去
    //         //(!batchOverWriting):true为添加模式 //否则false为覆盖模式
    //         resultArr.push(...(existedPickDoneArr ? existedPickDoneArr : []));
    //     }
    //     //else 覆盖模式只认已确认待添加列表:tempPickArr
    //
    //     //已确认待添加列表。//如果为空就是没选，也加进去 //非空则为选择了
    //     let tempPickArr = toRaw(showingLijuEntry.formsCountTempPickListMap.get(form));
    //     resultArr.push(...(tempPickArr ? tempPickArr : []));
    //
    //     if (resultArr.length > 0 || formNoSelectDeleteMode.value) {
    //         resultArr = orderBy(resultArr, [], ['asc']);
    //         if (existedPickDoneArr) {
    //             clearAndPushAll(showingLijuEntry.pickDoneFormsCountCheckedListMap.get(form), resultArr);
    //         } else {
    //             showingLijuEntry.pickDoneFormsCountCheckedListMap.set(form, resultArr);
    //         }
    //     }
    // })

    /**
     * to delete end.
     */


  })

  clearAllLijuEntryBatchModifyPendingConfirm();
  batchOperType.value = BatchOperType.None;
  batchDeletingTheForm.value = '';
}

function cancelAnyBatchPickFormsCountAction() {
  clearAllLijuEntryBatchModifyPendingConfirm();
  batchOperType.value = BatchOperType.None;
  batchDeletingTheForm.value = '';
}


provide(globalContextKey1, {
  batchMatchOverWriteAllTempPick,
  batchMatchAddAllTempPick,
  cancelAnyBatchPickFormsCountAction,
  confirmAllBatchTempPickIntoPickDone,
  batchDeleteAllPickedDoneOfForm
})

const KnownFormsSet = new Set(['n', 'v', 'adj', 'adv', 'n.idioms', 'v.idioms', 'v.phr', 'default']);

function extractForm(form) {
  if (form && form.trim().length > 0) {
    let formPart = form.substring(0, form.lastIndexOf('.'));
    let countPart = form.substring(form.lastIndexOf('.') + 1, form.length);
    let count = parseInt(countPart);
    if (formPart.trim().length === 0) {
      formPart = "default"
    }
    let isKnowForm = !isNaN(count) && KnownFormsSet.has(formPart);
    return {formPart, count, isKnowForm};
  } else {
    return undefined;
  }
}


/**
 * 批量修改操作部分 end
 */

let lastFormsInputValue = '';

function formsInputEnterUpped(e) {
  let formsInputValue = formsInputV.value.trim();
  if (!formsInputValue || formsInputValue === '') {
    formsCountMap.clear();
  }

  reInitAllCommonSwitch();

  function clearAllBatchPickCheckedList() {
    [...formsCountMap.values()].forEach(theValueObj => {
      clearAndPushAll(theValueObj?.checkedList, []);
    });
  }

  if (lastFormsInputValue !== formsInputValue) {

    batchIndividual.value = false;
    clearAllBatchPickCheckedList();

    batchFormsCntPickSw.value = true;
    // clearAndPushAll(formsCountArr, [])

    let forms = formsInputValue.split(' ');
    if (forms && forms.length === 1 && forms[0] === '') {
      lastFormsInputValue = '';
      return
    }

    [...formsCountMap.values()].forEach(formsCount => clearAndPushAll(formsCount.formCntArr, []));

    let unKnownForms = forms.filter(form => !extractForm(form)?.isKnowForm)

    let toAddFormCounts = difference(forms, unKnownForms).map(form => {
      let formPartsObj = extractForm(form);
      let formCntArr = [];
      for (let i = 1; i <= formPartsObj.count; i++) {
        formCntArr.push(formPartsObj.formPart + '.' + i);
      }
      return {form: formPartsObj.formPart, formCntArr}
    })

    toAddFormCounts.push({form: "other", formCntArr: unKnownForms.map(unknownForm => "other." + unknownForm)});

    // let otherTag = difference(forms,knownForms);
    for (const formCounts of toAddFormCounts) {
      let existedTheFormCountObj = formsCountMap.get(formCounts.form);
      if (existedTheFormCountObj) {
        //只改变带选择列表的formCntArr,checkedList不动
        clearAndPushAll(existedTheFormCountObj.formCntArr, formCounts.formCntArr);
      } else {
        formsCountMap.set(formCounts.form, {
          form: formCounts.form,
          formCntArr: formCounts.formCntArr,
          checkedList: []
        });
      }
    }
  } else {
    batchFormsCntPickSw.value = !batchFormsCntPickSw.value;
    if (!batchFormsCntPickSw.value) {
      clearAllLijuEntryBatchModifyPendingConfirm();//? todo 注释
    } else {
      batchIndividual.value = false;
    }
  }

  lastFormsInputValue = formsInputValue;
}

function batchIndividualChangeFunc() {
  if (batchIndividual.value) {
    batchFormsCntPickSw.value = false;
    // anyIndividualIsEditing.value = true;
  } else {
    // anyIndividualIsEditing.value = false;
    formsInputEnterUpped();
  }
}

let cptAllPickedDoneFormsCounts = computed(() => {
    // console.log("cptAllPickedDoneFormsCounts compute")
  let arrFormsCounts = flatedYoudaoLijuPatternMarkingTempArr.flatMap(theLijuEntry =>
      [...theLijuEntry.pickDoneFormsCountCheckedListMap.values()].flatMap(thePickedDoneArr => thePickedDoneArr)
  );

  return orderBy([...(new Set(arrFormsCounts))],
      pickDoneFormCount => {
        let formPartIndex = [...formsCountMap.entries()].findIndex(
            formsCountEntry => pickDoneFormCount?.substring(0, pickDoneFormCount.lastIndexOf('.')) === formsCountEntry[0]
        );

        let restPart = pickDoneFormCount?.substring(pickDoneFormCount.lastIndexOf('.') + 1); //其他，否

        if (pickDoneFormCount.indexOf("other.") === 0 && formsCountMap.has("other")) {
          restPart = formsCountMap.get("other").formCntArr.indexOf(pickDoneFormCount) + "";
        }

        return parseInt(formPartIndex + restPart);
      }, ["asc"]);
});

watch(cptAllPickedDoneFormsCounts,()=>{
    // console.log("watched cptAllPickedDoneFormsCounts");
    if(persistBackedExecuteEnd.value){
        let groupedBy = groupBy(cptAllPickedDoneFormsCounts.value, formcount => formcount.substring(0, formcount.lastIndexOf(".")));
        let backFormsInputArr = toPairs(groupedBy).flatMap(entry => {
            if (contains("adj n v adv n.idioms v.idioms v.phr", entry[0])) {
                return [max(entry[1])];
            } else if ("other" === entry[0]) {
                return entry[1].map(ele => ele.substring("other".length + 1));
            } else if ("default" === entry[0]) {
                return max(entry[1]).substring?.("default".length);
            }
        });

        formsInputV.value = backFormsInputArr.join(" ");
        formsInputEnterUpped();
        formsInputEnterUpped();
        // console.log("and updated the formsInputV value")
        persistBackedExecuteEnd.value= false;
    };
})


// watchEffect()

let theLabel = ref('');

function chooseThisTagAllLijus(label) {
  // console.log(theProps.label);
  chooseThisTagAllLijusVisible.value = true;
  theLabel.value = label;
}

let cptTheShowingLijus = computed(() => {
  return flatedYoudaoLijuPatternMarkingTempArr.filter(theLijuEntry => theLijuEntry.pickDoneFormsCountsHas(theLabel.value));
})

let filterTheResultFormsCountsCheckedList = ref([]);

function thisPageFilterShowingChangedFunc() {
  clearAndPushAll(filterTheResultFormsCountsCheckedList.value, []);
  invertFilterTheFormCountsRule.value = false;
}

const backEndUrl = "http://localhost:3000"
// const backEndUrl = "http://192.168.43.195:3000"

// let tempReactive = ref({});

let currBaseSaveFetchNVersion = ref({})

function persistBack(entry) {
  axios.post(backEndUrl + '/youdaoMarking/querySpecified', toRaw(entry)).then(function (response) {
    activeName.value = '';
    // console.log(response);
    showPersistBacked(response.data);
    currBaseSaveFetchNVersion.value = entry;
  }).catch(function (error) {
    console.error(error);
  });
}


let persistBackedExecuteEnd = ref(false);

// watch(persistBackedExecuteEnd,newValue=>{
//     console.log("persistBackedExecuteEnd change watched",newValue);
// })
// let showingLijus = ref(true);
function showPersistBacked(storedObj) {

  fetchedYoudaoLijuResultMap.clear();
  clearAndPushAll(replacedAllFormedFetchKeywordsArr, []);
  // showingLijus.value = false;
  // await nextTick();
  // setTimeout(()=>{
  fetchYoudaoLijusV.value = storedObj.fetchKeyWordsRaw;
  let storedArr = storedObj.resultLijuArr;
  storedArr.forEach(fetchKeyEntry => {
    replacedAllFormedFetchKeywordsArr.push(fetchKeyEntry.fetchKeyWord);
    let backedYoudaoLijuPatternMarkingArr = fetchKeyEntry.fetchedResultArr.map(lijuEntry => {
      // lijuEntry.youdaoLiju.chi = lijuEntry.youdaoLiju.chi.substring(0,lijuEntry.youdaoLiju.chi.length-tt);
      return plainToInstance(YoudaoLijuPatternMarkingTemp, lijuEntry);
    });

    fetchedYoudaoLijuResultMap.set(fetchKeyEntry.fetchKeyWord, backedYoudaoLijuPatternMarkingArr);
  });
// showingLijus.value = true;
  persistBackedExecuteEnd.value = true;

  // let groupedBy = groupBy(cptAllPickedDoneFormsCounts.value, formcount => formcount.substring(0, formcount.lastIndexOf(".")));
  // let backFormsInputArr = toPairs(groupedBy).flatMap(entry => {
  //   if (contains("adj n v adv n.idioms v.idioms v.phr", entry[0])) {
  //     return [max(entry[1])];
  //   } else if ("other" === entry[0]) {
  //     return entry[1].map(ele => ele.substring("other".length + 1));
  //   } else if ("default" === entry[0]) {
  //     return max(entry[1]).substring?.("default".length);
  //   }
  // });
  //
  // formsInputV.value = backFormsInputArr.join(" ");
  // formsInputEnterUpped();
  // formsInputEnterUpped();

}

function persistBackTest() {
  let storedObj = JSON.parse(localStorage.getItem("tempaa"));
  showPersistBacked(storedObj);
  // let result = plainToInstance(YoudaoLijuPatternMarkingTemp, sourceaaa);
  // fetchedYoudaoLijuResultMap.set("flee",[result]);
  // replacedAllFormedFetchKeywordsArr.push("flee");
  // tempReactive.value=result;
  // console.log('plainToInstance result', result);
}

function saveBackEnd() {

  let resultPersistArr = orderBy([...fetchedYoudaoLijuResultMap.entries()], fetchKeyEntry => replacedAllFormedFetchKeywordsArr.findIndex(
          formedFetchKey => formedFetchKey === fetchKeyEntry[0]
      ),
      ["asc"]).map(fetchWordEntry => {
    let persistRawsArr = toRaw(fetchWordEntry[1]).map(entry =>
        instanceToPlain(entry, {excludePrefixes: ['_'], strategy: 'excludeAll'}));
    return {fetchKeyWord: fetchWordEntry[0], fetchedResultArr: persistRawsArr};
  })

  // let sourceaaa = toPersistData.get('flee')[0];
  // sourceaaa.testpp = "ssssaa";

  let toPersistObj = {fetchKeyWordsRaw: fetchYoudaoLijusV.value, resultLijuArr: resultPersistArr};
  let currBaseSaveFetchNVersionRaw = toRaw(currBaseSaveFetchNVersion.value);
  if (!isEmptyObj(currBaseSaveFetchNVersionRaw)) {
    toPersistObj.modifyBaseOn = currBaseSaveFetchNVersionRaw;
  }

  localStorage.setItem("tempaa", JSON.stringify(toPersistObj));

  axios.post(backEndUrl + '/youdaoMarking/saveMarkedFetchYoudaoLijuMainMapEntry', toPersistObj).then(function (response) {
    queryAllSavedListFromBackEnd();
    // console.log(response);
  }).catch(function (error) {
    console.error(error);
  });
}

function queryAllSavedListFromBackEnd() {
  axios.get(backEndUrl + '/youdaoMarking/queryAllSavedList', {}).then(function (response) {
    clearAndPushAll(allMarkedVersions, [...response.data])
    // console.log(response);
  }).catch(function (error) {
    console.log(error);
  });
}

let markLijuSingleEntrys = [];

function refTheEntries(el) {
  if (el) {
    let theToIdx = sortedIndexBy(markLijuSingleEntrys, el, theEl => {
      // console.log("sorting",theEl?.$props?.theLijuEntry?.youdaoLiju?.eng,theEl?.$props?.theLijuEntry?.aIdx)
      return theEl?.$props?.theLijuEntry?.aIdx;
    });

    if (markLijuSingleEntrys[theToIdx]?.$props?.theLijuEntry?.aIdx !== el?.$props?.theLijuEntry?.aIdx) {
      el.keyBoardMoveFocusOutThis();
      markLijuSingleEntrys.splice(theToIdx, 0, el);
    }
    // markLijuSingleEntrys.push(el);
  }
}

let currEntryFocusingIdxRef = ref(-1);

provide(globalContextDataKey1, {
  flatedYoudaoLijuPatternMarkingTempArr,
  formsInputV,
  flatedCptShowingFetchedYoudaoLijuResultList,
  currEntryFocusingIdxRef
})

watchEffect(() => {
  if (currEntryFocusingIdxRef.value !== -1) {
    readingModeSw.value = true;
  }

})

watchEffect(() => {
  if (!readingModeSw.value) {
    markLijuSingleEntrys?.[currEntryFocusingIdxRef.value]?.keyBoardMoveFocusOutThis();
    currEntryFocusingIdxRef.value = -1;
    reInitAllCommonSwitch();
  }

})

const shortCutKeysEventCenter = {
  eventProcessFuncs: new Map([[',@,@', []], [',/,/', []], ['Alt+q', []], ['Alt+r', []], ['Alt+d', []]]),
  subscribe: function (shortCuts, eventProcessFunc) {
    if (this.eventProcessFuncs.get(shortCuts)?.indexOf(eventProcessFunc) < 0) {
      this.eventProcessFuncs.get(shortCuts)?.push(eventProcessFunc);
    }
  },
  unSubscribe: function (shortCuts, eventProcessFunc) {
    remove(this.eventProcessFuncs.get(shortCuts), registeredFunc => registeredFunc === eventProcessFunc);
  },
  fire: function (shortCuts, ...params) {
    this.eventProcessFuncs.get(shortCuts).forEach(eventProcessFunc => {
      eventProcessFunc(...params);
    })
  }
}


// shortCutKeysEventCenter.subscribe("Alt+d",(a,b,c)=>{console.log("received,",a,b,c)});

let preKeys = {keyedKeys: '', keyCnt: 0};

function scrollTheRefIntoView(theEntryRef) {
  let theTargetDom = theEntryRef.$el.nextElementSibling;
  // let elementPosition = theTargetDom.getBoundingClientRect();
  // theTargetDom.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
  // theTargetDom.scrollIntoView({ block: "start", inline: "nearest" });
  theTargetDom.scrollIntoView({block: "center", inline: "nearest"});
}

// let currEntryFocusingIdx=-1;
onMounted(() => {
  queryAllSavedListFromBackEnd();
  document.addEventListener("keydown", (e) => {
    // console.log("app added",e);
    if (markLijuSingleEntrys && markLijuSingleEntrys.length > 0) {
      if (e.ctrlKey) {
        // console.log("ctrl keyed");
        if (e.key === 'ArrowDown' && currEntryFocusingIdxRef.value !== markLijuSingleEntrys.length - 1) {
          currEntryFocusingIdxRef.value++;
          // console.log("ArrowDown keyed with currEntryFocusingIdxRef.value:",currEntryFocusingIdxRef.value);
          if (currEntryFocusingIdxRef.value !== 0) {
            markLijuSingleEntrys[currEntryFocusingIdxRef.value - 1].keyBoardMoveFocusOutThis();
          }
          markLijuSingleEntrys[currEntryFocusingIdxRef.value].keyBoardMoveFocusThis();

          // console.log("target:",markLijuSingleEntrys[currEntryFocusingIdxRef.value]);
          let theTargetDom = markLijuSingleEntrys[currEntryFocusingIdxRef.value].$el.nextElementSibling;
          let elementPosition = theTargetDom.getBoundingClientRect();
          // theTargetDom.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
          // theTargetDom.scrollIntoView({ block: "end", inline: "nearest" });
          if (currEntryFocusingIdxRef.value > 3) {
            theTargetDom.scrollIntoView({block: "center", inline: "nearest"});
          }
          // console.log("theTargetDom",theTargetDom.scrollIntoView);
          // console.log("elementPosition bottom:",elementPosition.top + elementPosition.height);
          // console.log("window.innerHeight:",window.innerHeight);
          // console.log("window.pageYOffset:",window.pageYOffset);
          // let targetElementBottom = window.innerHeight + window.pageYOffset - (elementPosition.top + elementPosition.height);
          // window.scrollTo(0, targetElementBottom);


        } else if (e.key === 'ArrowUp' && currEntryFocusingIdxRef.value !== -1) {
          currEntryFocusingIdxRef.value--;
          // console.log("ArrowUp keyed with currEntryFocusingIdxRef.value:",currEntryFocusingIdxRef.value);
          markLijuSingleEntrys[currEntryFocusingIdxRef.value + 1].keyBoardMoveFocusOutThis();
          if (currEntryFocusingIdxRef.value !== -1) {
            let theEntryRef = markLijuSingleEntrys[currEntryFocusingIdxRef.value];
            theEntryRef.keyBoardMoveFocusThis();
            scrollTheRefIntoView(theEntryRef);
          }
        } else if (e.key === 'ArrowLeft' && currEntryFocusingIdxRef.value !== -1) {
          markLijuSingleEntrys[currEntryFocusingIdxRef.value].keyBoardMoveLeft();
        } else if (e.key === 'ArrowRight' && currEntryFocusingIdxRef.value !== -1) {
          markLijuSingleEntrys[currEntryFocusingIdxRef.value].keyBoardMoveRight();
        }
      } else if (e.altKey) {
        // console.log("alt+,",e.key)
        if (e.key === 'q'||e.key === 'Q') {
          e.preventDefault();
          // console.log("Alt+q hit")
          shortCutKeysEventCenter.fire('Alt+q');
        } else if (e.key === 'r'||e.key === 'R') {
          console.log("alt + r");
          readingModeSw.value = !readingModeSw.value;
          e.preventDefault();
        } else if (e.key === 'd'||e.key === 'D') {
          console.log("alt + d");
          allDetailing.value = !allDetailing.value;
          if (readingModeSw.value && currEntryFocusingIdxRef.value > -1) {

            (async () => {
              await nextTick();
              scrollTheRefIntoView(markLijuSingleEntrys[currEntryFocusingIdxRef.value]);
            })()
          }
          // shortCutKeysEventCenter.fire('Alt+d',1,"r",3);
          e.preventDefault();
        }
      }
    }

    if (new Set(['Tab', 'ArrowDown', 'ArrowUp', 'Escape']).has(e.key)) {
      e.preventDefault();
    }
    if (!new Set(['Shift', 'Alt', 'Control']).has(e.key)) {
      preKeys.keyedKeys += ',' + e.key;
      preKeys.keyCnt++;
      if (preKeys.keyCnt >= 2) {
        // console.log("keyed:",preKeys.keyedKeys);
        if (',@,@' === preKeys.keyedKeys || ',/,/' === preKeys.keyedKeys) {
          e.preventDefault();
          console.log("fire ,", preKeys.keyedKeys);
          shortCutKeysEventCenter.fire(preKeys.keyedKeys);
        }
      }
    }

    setTimeout(() => {
      preKeys.keyedKeys = '';
      preKeys.keyCnt = 0
    }, 1000);
  }, false);

})

let showShortCutSelect = ref(false);
let theShortCutSelect = ref();
shortCutKeysEventCenter.subscribe(',/,/', () => {
  if (currEntryFocusingIdxRef.value !== -1) {
    showShortCutSelect.value = true;
    (async () => {
      await nextTick();
      theShortCutSelect?.value.focus?.();
    })();
  }
})

const shortCutsSeletedValue = ref('-1')

function shortCutsSelectVisibleChanged(visible) {
  console.log("shortCutsValueSeleted :", shortCutsSeletedValue.value);
  if(!visible){
    showShortCutSelect.value = false;
    if(shortCutsSeletedValue.value===`phrase`){
      markLijuSingleEntrys[currEntryFocusingIdxRef.value].toAddPhrases();
    }else if(shortCutsSeletedValue.value===`word`){
      markLijuSingleEntrys[currEntryFocusingIdxRef.value].toAddWords();
    }
    shortCutsSeletedValue.value = 'phrase'
  }
  //
}

function shortCutsSelectChanged(){
    showShortCutSelect.value = false;
    if(shortCutsSeletedValue.value===`phrase`){
        markLijuSingleEntrys[currEntryFocusingIdxRef.value].toAddPhrases();
    }else if(shortCutsSeletedValue.value===`word`){
        markLijuSingleEntrys[currEntryFocusingIdxRef.value].toAddWords();
    }
    shortCutsSeletedValue.value = '-1'
}

const shortCutsOptions = [
  {
    value: 'phrase',
    label: 'phrase',
  },
  {
    value: 'word',
    label: 'word',
  },
  {
    value: 'etymonline',
    label: 'etymonline',
  },
  {
    value: 'topics',
    label: 'topics',
  },
  {
    value: '@@',
    label: '@@',
  },
  {
    value: 'synonyms',
    label: 'synonyms',
  },
  {
    value: 'see also',
    label: 'see also',
  }, {
    value: 'opposite',
    label: 'opposite',
  },
]

provide(globalShortCutKeysEventCenter, {
  center: shortCutKeysEventCenter
})

const activeName = ref('1');

let allMarkedVersions = reactive([]);

let showTest = ref(true);
const drawer = ref(false);
const innerDrawer = ref(false);

function tagChangeTestFunc1(status) {
  // console.log(status);
}

function anyTagChanged() {
  // maskNotMatched.value = false;
}

function testfunc1(status) {
  setTimeout(() => {
    // console.log("testfunc1 end");
  }, 3000);
}

let testPopVisible1 = ref(false);
let testPopVisible2 = ref(false);

</script>

<template>

  <div v-show="showTest">
    <!--      fetchedYoudaoLijuResultMap:{{fetchedYoudaoLijuResultMap}}-->
    <!--      <br/>-->
    <!--      cptShowingFetchedYoudaoLijuResultList:{{cptShowingFetchedYoudaoLijuResultList}}-->
    invertInputPatternMatchRule:{{ invertInputPatternMatchRule }}
    <br/>
    {{ batchFormsCntPickSw }}
    {{ batchOperType }}\{{ batchDeletingTheForm }}
    <br/>
    anyIndividualIsEditing:{{ anyIndividualIsEditing }}
    <el-button plain @click="buttonsTestVisible = true">
      buttons
    </el-button>
    <el-dialog v-model="buttonsTestVisible" title="buttons" width="800">
      <ButtonsTest></ButtonsTest>
    </el-dialog>
    <el-button plain @click="tagsTestVisible = true">
      tags
    </el-button>
    <el-dialog v-model="tagsTestVisible" title="tags" width="800">
      <TagsTest></TagsTest>
    </el-dialog>
    <el-button plain @click="testCompVisible = true">
      test1
    </el-button>
    <el-dialog v-model="testCompVisible" title="test1" width="800">
      <Test1Comp></Test1Comp>
    </el-dialog>
    <el-button plain @click="testModelDefineVisible = true">
      testModelDefine
    </el-button>
    <el-dialog v-model="testModelDefineVisible" title="model define" width="800">
      <Test2Comp></Test2Comp>
    </el-dialog>
    <el-button plain @click="testComp3Visible = true">
      Test3Comp
    </el-button>
    <el-dialog v-model="testComp3Visible" title="comp1" width="800">
      <Test3Comp :label="`n.idioms.3`"></Test3Comp>
      <!--          <Test3Comp :label="`v.1`"></Test3Comp>-->
    </el-dialog>


    <el-button plain @click="testComp4Visible = true">
      Test4Comp
    </el-button>
    <el-dialog v-model="testComp4Visible" title="comp4" width="800">
      <Test4Comp :label="`v.1`"></Test4Comp>
    </el-dialog>
    <el-button plain @click="testComp5Visible = true">
      Test5Comp
    </el-button>
    <el-dialog v-model="testComp5Visible" title="comp5" width="100%">
      <Test5Comp></Test5Comp>
    </el-dialog>
    <el-button plain @click="testComp6Visible = true">
      Test6Comp
    </el-button>
    <el-dialog v-model="testComp6Visible" title="comp5" width="100%">
      <Test6Comp></Test6Comp>
    </el-dialog>

      <el-button plain @click="testComp7Visible = true">
          Test7Comp
      </el-button>
      <el-dialog v-model="testComp7Visible" title="comp5" width="100%">
          <Test7Comp></Test7Comp>

      </el-dialog>

    <el-button type="primary" style="margin-left: 16px" @click="drawer = true">
      open
    </el-button>

    <el-drawer v-model="drawer" title="I'm outer Drawer" size="96%" :direction="`ttb`">
      <div>
        <el-button @click="innerDrawer = true">Click me!</el-button>
        <el-drawer
            v-model="innerDrawer"
            title="I'm inner Drawer"
            :append-to-body="true"
            size="92%"
            :direction="`ttb`"
        >
          <el-scrollbar height="400px">
            <p v-for="item in 50" :key="item" class="scrollbar-demo-item">{{ item }}</p>
          </el-scrollbar>

          <p>_(:зゝ∠)_</p>
        </el-drawer>
      </div>
    </el-drawer>

    <br/>
    theCOumt:{{ flatedCptShowingFetchedYoudaoLijuResultList.length }}
    <br/>
    theCOumt1:{{ flatedYoudaoLijuPatternMarkingTempArr.length }}
    <br/>
    <br/>
  </div>
  <div v-show="showShortCutSelect" style="z-index:1000;position: fixed;top:250px;left:750px;width: 300px;height: 50px;background-color: rgba(210,225,246,0.56);padding-top: 10px;padding-left: 10px;border-radius: 5px;border: 1px solid">
<!--    <el-text>//</el-text>-->
<!--      @visibleChange="shortCutsSelectVisibleChanged"-->
    <el-select
        ref="theShortCutSelect"
        v-model="shortCutsSeletedValue"
        @change="shortCutsSelectChanged"
        @keyup.esc.exact="showShortCutSelect = false"
        default-first-option
        filterable
        placeholder="Select"
        style="width: 240px;margin-left: 5px"
    >
      <el-option
          v-for="item in shortCutsOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
  </div>


    <el-popover placement="bottom-start" :width="500" trigger="click" :visible="testPopVisible1">
        <template #reference>
            <el-button style="margin-right: 16px" @click="testPopVisible1 = !testPopVisible1">Click to activate</el-button>
        </template>
        <div>
          <TinyMCETest1></TinyMCETest1>
        </div>
    </el-popover>
    <el-popover placement="bottom-start" :width="`fit-content`" trigger="click" :visible="testPopVisible2">
        <template #reference>
            <el-button style="margin-right: 16px" @click="testPopVisible2 = !testPopVisible2">Click to activate</el-button>
        </template>
        <div>
            <Test8Comp :thePopVisible="testPopVisible2"></Test8Comp>
        </div>
    </el-popover>

<!--    <div style="width: 700px;height: 200px">-->
<!--        <TinyMCETest1></TinyMCETest1>-->
<!--    </div>-->

  <table>
    <tr style="vertical-align: top;border: #181818 2px">
      <td style="width: 350px">
                <textarea ref="fetchYoudaoLijus"
                          @keyup="fetchYoudaoLijusUpped"
                          v-model="fetchYoudaoLijusV"
                          style="resize: vertical;height: 70px;width: 100%"/>
        <div desc="chooseBtns" style="display: flex" v-if="cptAllPickedDoneFormsCounts.length>0">
          <div style="margin-top: 5px;width: 220px" v-if="!thisPageFilterShowing">
            <PickedDoneFormCountLijusShowingButton v-for="(formCount,idx) in cptAllPickedDoneFormsCounts"
                                                   :label="formCount"/>
          </div>
          <div v-else style="margin-top: 3px;width: 220px">
            <WordFormedTagGroup v-model="filterTheResultFormsCountsCheckedList">
              <WordFormedCheckTag v-for="(formCount,idx) in cptAllPickedDoneFormsCounts"
                                  :label="formCount" :plain="true"
                                  @change="anyTagChanged"></WordFormedCheckTag>
            </WordFormedTagGroup>

            <!--                        {{filterAllAndMode?filterTheResultFormsCountsCheckedList.join(`&`):filterTheResultFormsCountsCheckedList.join(`|`)}}-->


            <el-switch v-model="filterAllAndMode"
                       inline-prompt
                       style="--el-switch-on-color: #13ce66; --el-switch-off-color: #1e55dc"
                       active-text="且"
                       inactive-text="或"
                       @change="status=>{if(!status){exactOrInclude=false}}"/>
            <el-switch v-model="exactOrInclude"
                       v-if="filterAllAndMode"
                       inline-prompt
                       active-text="精确"
                       inactive-text="包含"
                       style="margin-left: 3px;--el-switch-on-color: #13ce66; --el-switch-off-color: #1e55dc"/>
          </div>
          <div style="margin-top: 2px;margin-left: 5px">
            <el-switch v-model="thisPageFilterShowing" @change="thisPageFilterShowingChangedFunc"/>&nbsp;当前页过滤

            <span v-if="thisPageFilterShowing"><br/><el-switch v-model="invertFilterTheFormCountsRule"/>&nbsp;反选
                        <br/><button class="my-button"
                                     @click="clearAndPushAll(filterTheResultFormsCountsCheckedList,[...toRaw(cptAllPickedDoneFormsCounts?cptAllPickedDoneFormsCounts:[])])">全选</button>
                        <br/><button class="my-button" style="margin-top: 5px"
                                     @click="clearAndPushAll(filterTheResultFormsCountsCheckedList,[])">清空</button></span>
          </div>
          <!--                    filterTheResultFormsCountsCheckedList:{{filterTheResultFormsCountsCheckedList}}-->
          <!--                    <BatchOverWritingTag :label="`v.1`" :theForm="`v`"/>-->

          <!--                    {{innerDrawer}}-->
          <!--                    {{ cptAllPickedDoneFormsCounts }}-->
          <!--                    <FormsCountBtn v-for="(formCount,idx) in cptAllPickedDoneFormsCounts" :label="formCount" @click="chooseThisTagAllLijus"></FormsCountBtn>-->
          <!--                    <el-dialog v-model="chooseThisTagAllLijusVisible"-->
          <!--                               destroy-on-close-->
          <!--                               draggable-->
          <!--                               overflow-->
          <!--                               :modal="true"-->
          <!--                               title="对应例句:"-->
          <!--                               width="80%" id="dialog-test1">-->
          <!--&lt;!&ndash;                                1:{{cptTheShowingLijus}}&ndash;&gt;-->
          <!--                        <div v-for="(theLijuEntry,idx) in cptTheShowingLijus">-->
          <!--                            <el-text>{{theLijuEntry.eng}}</el-text>-->
          <!--                            <br/>-->
          <!--                            <el-text>{{theLijuEntry.chi}}</el-text>-->
          <!--                        </div>-->
          <!--                    </el-dialog>-->
        </div>

      </td>
      <td style="width: 100px;text-align: center">
        <el-button
            ref="fetchLijuButton"
            type="primary"
            @click="fetchYoudaoLijusFunc"
            :disabled="buttonDisabled">
          有道例句
        </el-button>
      </td>

      <!--      <td style="width: 380px;border: #181818 2px dotted">-->
      <td style="width: 380px">
        <textarea ref="inputMatchPatternRef"
                  @keyup="inputMatchKeyUpped"
                  @focusin="disableFetchYoudaoLijus"
                  @focusout="enableFetchYoudaoLijus"
                  v-model="inputMatchPatternV"
                  style="resize: vertical;height: 40px;width: 98%"/>
        <!--                <div v-show="inputMatchPatternV&&inputMatchPatternV!==''&&flatedCptShowingFetchedYoudaoLijuResultList.length!==flatedYoudaoLijuPatternMarkingTempArr.length">-->
        <textarea v-model="formsInputV"
                  @keyup.ctrl.enter.exact="formsInputEnterUpped"
                  style="resize: vertical;height: 32px;width: 98%"/>
        <!--                <div v-show="batchFormsCntPickSw">-->

        <div>
          <FormCheckGroups :formsCountMap="formsCountMap" :isBatchMatch="true"
                           :batchFormsCntPickSw="batchFormsCntPickSw"></FormCheckGroups>
          <!--                    theMode:{{formNoSelectDeleteMode}}-->

        </div>

        <!--                </div>-->
      </td>
      <td style="width: 200px;">
        <el-button type="danger" :icon="Delete" @click="clearInputMatchPattern" :size="`small`"/>
        <!--                <el-button type="danger" :icon="Delete" @click="clearInputMatchPattern" circle/>-->
        <br/>
        <el-switch v-model="maskNotMatched" @change="maskNotMatchedChanged"/>&nbsp;隐藏未匹配
        <br/>
        <!--                <el-switch v-model="invertInputPatternMatchRule" :disabled="!maskNotMatched"/>&nbsp;反选-->
        <el-switch v-model="invertInputPatternMatchRule" @change="testfunc1"/>&nbsp;反选
        <br/>
        <el-switch v-model="batchIndividual" :disabled="formsCountMap.size===0"
                   @change="batchIndividualChangeFunc"/>&nbsp;批单模式

      </td>
    </tr>
  </table>
  <!--    <br/>-->

  <!--    <br/>-->
  <div :style="{
          boxShadow: `var(${getCssVarName('lighter')})`,
          padding: `10px`,
          width: `600px`,
        }"
       @click="testSome1"
  >
    <div style="display: flex">
      <el-switch v-model="readingModeSw"/>&nbsp;<el-text>阅读模式</el-text>
      <div style="padding-left: 10px"></div>
      <PickedDoneFormCountLijusShowingButton
          :label="filterAllAndMode?filterTheResultFormsCountsCheckedList.join(`&`):filterTheResultFormsCountsCheckedList.join(`|`)"
          :display="`other.批量操作`"/>
      <button class="my-button" style="margin-left: 5px" @click="saveBackEnd">保存</button>
      <button class="my-button" style="margin-left: 5px" @click="persistBackTest">回来</button>
      <!--                  <button class="my-button" style="margin-left: 5px" @click="fetchedYoudaoLijuResultMap.clear();clearAndPushAll(replacedAllFormedFetchKeywordsArr,[]);">qing</button>-->
    </div>
    <div style="display: flex">
      <el-switch v-model="allDetailing"/>&nbsp;<el-text>细节</el-text>
    </div>
    <el-collapse v-model="activeName" accordion>
      <!--            <el-collapse-item title="操作" name="1" class="my-collapse-item">-->
      <!--            </el-collapse-item>-->
      <el-collapse-item title="历史标注过" name="2" class="my-collapse-item">
        <div v-for="(entry,idx) in allMarkedVersions">
          <button class="my-button" style="margin-top: 3px" @click="persistBack(entry)">
            {{ entry.fetchKeyWordsRaw }} //
            version.{{ entry.version }}
          </button>
          <el-text style="margin-left: 5px" v-if="entry.baseOnFetchInfo">baseOn:
            {{ entry?.baseOnFetchInfo?.fetchKeyWordsRaw }} // {{ entry?.baseOnFetchInfo?.version }}
          </el-text>
        </div>
        {{ currBaseSaveFetchNVersion }}
      </el-collapse-item>
      <el-collapse-item title="verbForms" name="3" v-if="verbFormMapping.size>0" class="my-collapse-item">
        <div v-for="theVerbForm in verbFormMapping.entries()">
          {{ theVerbForm }}
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>


  <!--    <br/>-->
  <!--    mark11111:-->
  <!--    <br/>-->
  <!--    <div v-for=" (lijus,idx) in cptShowingFetchedYoudaoLijuResultList">-->
  <!--        {{lijus}}-->
  <!--    </div>-->
  <!--    <br/>-->
  <!--    <br/>-->
  <!--    <div v-if="verbFormMapping&&verbFormMapping.size>0"-->
  <!--         :style="{-->
  <!--          boxShadow: `var(${getCssVarName('lighter')})`,-->
  <!--          padding: `10px`,-->
  <!--          width: `600px`,-->
  <!--        }">-->
  <!--        -->
  <!--    </div>-->
  <br/>
  <!--       @keyup.ctrl.up.exact="console.log(`ctrl upped`)"-->
  <!--       @keyup.ctrl.down.exact="console.log(`ctrl downed`)"-->
  <div v-show="cptShowingFetchedYoudaoLijuResultList&&cptShowingFetchedYoudaoLijuResultList.length>0"
       :style="{
          boxShadow: `var(${getCssVarName('lighter')})`,
          padding: `10px`,
          width: `980px`,
        }">
    <TagBaseWord :label="`merge`"></TagBaseWord>
<!--      <div v-for="(entries,idxEntries) in showingFetchedYoudaoLijuResultList" :key="entries.replacedKeyword">-->
<!--          {{entries[1]}}-->
<!--      </div>-->
    <div v-for="(entries,idxEntries) in showingFetchedYoudaoLijuResultList" :key="entries.replacedKeyword">
      <div style="padding-bottom: 10px">
        <el-text>{{entries[0]}} :</el-text>
      </div>

      <!--                           ref="markLijuSingleEntrys"-->
      <!--        :ref="el=>console.log(`v-for the el`,el?.$?.props?.theLijuEntry?.youdaoLiju?.eng,el?.$?.props?.theLijuEntry?.uniqueId)"-->
      <!--        :ref="el=>{if(el){markLijuSingleEntrys.push(el)}}"-->
        <div v-for=" (entry,idxEntry) in entries[1]" :key="entry.uniqueId" v-show="entry.toShow">
          <MarkLijuSingleEntry
                               :ref="refTheEntries"
                               :theLijuEntry="entry"
                               :maskNotMatched="maskNotMatched"
                               :batchOperType="batchOperType"
                               :formsCountMap="formsCountMap"
                               :batchIndividual="batchIndividual"
                               :batchFormsCntPickSw="batchFormsCntPickSw"
                               :allDetailing="allDetailing"
                               @iamFocused="aIdx=>{markLijuSingleEntrys[currEntryFocusingIdxRef]?.keyBoardMoveFocusOutThis?.();currEntryFocusingIdxRef=aIdx}"
          ></MarkLijuSingleEntry>
        </div>

      <br/>
      <br/>
    </div>
  </div>

</template>

<style scoped>


:global(.group0-hilight) {
  background-color: #f6e955;
}

:global(:root) {
  --color-nounsOut: #0765c9;
  --color-nounsOut-clickdarker: #01468d;
  --color-nounsOut-bg-color-editing: #97bae3;
  --color-nounsOut-bg-color: #d3ebff;

  --color-verbsOut: #0a863b;
  --color-verbsOut-clickdarker: #006727;
  --color-verbsOut-bg-color-editing: #9bdab2;
  --color-verbsOut-bg-color: #d1ffe2;

  --color-adjsOut: #b7670b;
  --color-adjsOut-clickdarker: #914e01;
  --color-adjsOut-bg-color-editing: #dab287;
  --color-adjsOut-bg-color: #ffe1c0;

  --color-advsOut: #654c12;
  --color-advsOut-clickdarker: #563b00;
  --color-advsOut-bg-color-editing: #ceb882;
  --color-advsOut-bg-color: #ffebbe;

  --color-nounIdiomsOut: #4c28cb;
  --color-nounIdiomsOut-clickdarker: #240498;
  --color-nounIdiomsOut-bg-color-editing: #917dce;
  --color-nounIdiomsOut-bg-color: #ccbeff;

  --color-verbIdiomsOut: #650595;
  --color-verbIdiomsOut-clickdarker: #460167;
  --color-verbIdiomsOut-bg-color-editing: #b580d5;
  --color-verbIdiomsOut-bg-color: #eac3ff;

  --color-verbPhrsOut: #950578;
  --color-verbPhrsOut-clickdarker: #690156;
  --color-verbPhrsOut-bg-color-editing: #d281ba;
  --color-verbPhrsOut-bg-color: #ffbef2;
  //--color-theFormOut: #000000; --color-formOut-default: #000000; --color-formOut-default-bg-color-editing: #8c8c8c; --color-formOut-default-bg-color: #8c8c8c; --color-other: #07b9ac; --color-other-clickdarker: #008072; --color-other-bg-color-editing: #7dd5cf; --color-other-bg-color: #a7f6f0;

  --color-default1: #0047a4;
  --color-default1-clickdarker: #003275;
  --color-default1-bg-color-editing: #7e9fcc;
  --color-default1-bg-color: #b4d1fc;
}

:global(:root .el-text) {
  color: var(--el-color-black);
  font-size: 14px;
}

:global(:root) {
  --common-tag-height: 20px;
}

header {
  line-height: 1.5;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }
}
</style>

<style>
.my-button-group {
  padding-top: 5px;
}

.my-button-group > .my-button:not(:first-child):not(:last-child) {
  border-radius: 0;
}

.my-button-group > .my-button:not(:last-child) {
  margin-right: -1px;
}

.my-button-group > .my-button:first-child {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-right-color: rgba(255, 255, 255, 0.5);
}

.my-button-group > .my-button:last-child {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.my-button:hover {
  background-color: #409eff;
  color: #ffffff;

}

.my-button:active {
  background-color: #337ecc;
  color: #ffffff;
}

.my-button {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
  --el-button-bg-color: #ecf5ff;
  white-space: nowrap;
  //cursor: pointer; color: var(--el-button-text-color); text-align: center; box-sizing: border-box; outline: 0; transition: .1s; font-weight: var(--el-button-font-weight); -moz-user-select: none; -ms-user-select: none; user-select: none; vertical-align: middle; -webkit-appearance: none; background-color: var(--el-button-bg-color); //background-color: #ecf5ff; border: var(--el-border); //border-color: var(--el-button-border-color); border-color: #a0cfff; border-radius: 3px; padding: 12px 8px; height: 25px; cursor: pointer;
}
</style>


<style scoped>
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
</style>

<style scoped>

.el-collapse-item.my-collapse-item :deep(.el-collapse-item__header) {
  height: 30px;
}
</style>